<template>
  <div class="bre-toolbar__optbtn__lab" @click="handleClick">直播</div>
  <BreModal v-model="modalDisplay" title="添加直播卡片">
    <div class="bre-link-modal__form">
      <div class="bre-input medium">
        <BreInput
          v-model="form.link"
          placeholder="请输入直播房间号或直播间链接"
          size="medium"
        />
      </div>
      <div class="bre-link-modal__form__btns">
        <BreButton
          size="small"
          type="primary"
          @click="handleEnter"
          class="bre-link-modal__btn"
        >
          确认
        </BreButton>
        <BreButton
          size="small"
          type="grey"
          @click="handleCancel"
          class="bre-link-modal__btn"
        >
          取消
        </BreButton>
      </div>
    </div>
  </BreModal>
</template>
<script setup lang="ts">
import BreInput from '../../components/BreInput.vue'
import BreButton from '../../components/BreButton.vue'
import BreModal from '../../components/BreModal.vue'
import { ref, shallowRef, inject } from 'vue'
import Quill from 'quill'
const QuillEditor = inject('QuillEditor', shallowRef<Quill>())

const modalDisplay = ref(false)
const form = ref({
  link: 'https://live.bilibili.com/22478506?live_from=82002',
})
const handleClick = () => {
  modalDisplay.value = true
}
const handleEnter = () => {
  try {
    const itemId = validator(form.value.link) //返回商品卡片id
    // 请求接口获取卡片信息
    QuillEditor.value?.insertLiveCard({
      id: `${itemId}`, //卡片对应类型id
      alt: 'undefined',
      size: null,
    })
    modalDisplay.value = false
  } catch (error) {
    console.warn(error)
  }
}
const handleCancel = () => {
  form.value.link = ''
  modalDisplay.value = false
}
const validator = (t: string) => {
  if (!(t = t.trim())) throw new Error('请输入视频链接')
  let match = t.match(/\d+/)
  if (match?.[0]) return 'lv' + match[0]
  throw new Error('无效的直播信息')
}
</script>
<style lang="scss" scoped></style>
